package com.entity

import com.CustomScript
import com.entity.ScriptName.*
import com.utils.ScriptUtils
import kotlin.reflect.KFunction
import kotlin.reflect.jvm.javaMethod

sealed class PathUnionType() {
    data class PathType(val value: PackPath) : PathUnionType()
    data class StringType(val value: String) : PathUnionType()
}

data class Script(

    /** 执行完成一次文件整理 检查执行的命令 */
    var completeOnceCheck: (() -> Unit)? = null,
    /** 执行替换 */
    var onReplace: (() -> Unit)? = null,
    /** 处理入口文件配置 */
    var onChangeIndex: (() -> Unit)? = null,
    /** 执行压缩 */
    var onCompress: (() -> Unit)? = null,
    /** 打包开始 */
    var subpackageStart: (() -> Unit)? = null,
    /** 打包结束 */
    var subpackageEnd: (() -> Unit)? = null,
    /** 上传服务 */
    var onUpload: (() -> Boolean)? = null,
    /**
     * 自定义执行流程脚本
     */
    var customScript: MutableList<CustomScript> = mutableListOf(),
    /**
     * 自定义可执行方法
     */
    var methodMap: MutableMap<String, KFunction<*>> = mutableMapOf(),
    /**
     * 自定义的属性值
     */
    var property: MutableMap<String, Any> = mutableMapOf(),
    /**
     * 加载新脚本路径
     * @param Any  String或Path
     */
    var loadFile: (path: List<PathUnionType>) -> Unit

) {
    lateinit var packCmd: PackCmd

    fun runCustomScript(function: KFunction<*>?) {
        if (function == null) return
        customScript.forEach {
            function.javaMethod?.invoke(it)
        }
    }

    fun loadScript(vararg scriptName: ScriptName) {
        val paths = scriptName.map {
            when (it) {
                COMPRESS, REPLACE, UPLOAD, PUSH_SFTP, GAME_EXTEND, CRC_RENAME, EXETEND_CMD -> {
                    val name = it.name.lowercase()
                        .split("_")
                        .onEach { value ->
                            value.replaceFirstChar { v -> v.uppercase() }
                        }
                        .joinToString("")

                    PathUnionType.PathType(PackPath(ScriptUtils.basePath, "$name.kts"))

                }
            }
        }
        loadFile.invoke(paths)
    }

}

enum class ScriptName {
    COMPRESS,
    REPLACE,
    UPLOAD,
    PUSH_SFTP,
    GAME_EXTEND,
    CRC_RENAME,
    EXETEND_CMD,
}